package com.example.demo.thread;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Classname PrintThreadWithThreadPool
 * @Description
 * @Date 2023/12/12 15:54
 * @Created by jyl
 *
 *  线程池实现两个线程交替打印
 */
public class PrintThreadWithThreadPool  {
    private static final AtomicInteger flag = new AtomicInteger(0);
    private static final ReentrantLock lock = new ReentrantLock();
    private static final Condition condition1 = lock.newCondition();
    private static final Condition condition2 = lock.newCondition();

    public static void main(String[] args) {
        ExecutorService executorService = Executors.newFixedThreadPool(2);

        executorService.submit(new PrintThread1());
        executorService.submit(new PrintThread2());


        executorService.shutdown();
    }

    static class PrintThread1 implements Runnable {
        @Override
        public void run() {
            for (int i = 0; i < 4; i++) {
                lock.lock();
                try {
                    while (flag.get() % 2 != 0) {
                        condition1.await();
                    }
                    System.out.println("线程1打印" + flag.getAndIncrement());
                    condition2.signal();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                } finally {
                    lock.unlock();
                }
            }
        }
    }

    static class PrintThread2 implements Runnable {
        @Override
        public void run() {
            for (int i = 0; i < 4; i++) {
                lock.lock();
                try {
                    while (flag.get() % 2 == 0) {
                        condition2.await();
                    }
                    System.out.println("线程2打印" + flag.getAndIncrement());
                    condition1.signal();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                } finally {
                    lock.unlock();
                }
            }
        }
    }
}
